package com.buaa.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;



public class DBUtil {

	private static String driver="oracle.jdbc.driver.OracleDriver";
	private static String url="jdbc:oracle:thin:@localhost:1521:orcl";
	private static String username="hyf";
	private  static String password="123";
	private static Connection conn;
	private static PreparedStatement ps;
	private static ResultSet rs;
	
	public static Connection getConnection(){
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url,username,password);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return conn;
	}
	
	public static ResultSet query(String sql, List<Object> param) throws SQLException{
		ps = conn.prepareStatement(sql);
		if(param!=null && param.size()>0) {
			for(int i=0;i<param.size();i++) {
				ps.setObject(i + 1, param.get(i));
			}
		}
		rs = ps.executeQuery();
		return rs;
	}
	
	public static void update(String sql,List<Object> param) throws SQLException{
		ps=conn.prepareStatement(sql);
		if(param!=null && param.size()>0){
			for (int i = 0; i < param.size(); i++) {
				ps.setObject(i+1, param.get(i));
			}
		}
		ps.executeUpdate();
	} 
	
	public static void close(){
		try {
			if(rs!=null){
				rs.close();
			}
			if(ps!=null){
				ps.close();
			}
			if(conn!=null){
				conn.close();
			}
			
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
}
